package org.zjkoye.crm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.micrometer.common.lang.Nullable;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zjkoye.crm.common.PageResultBean;
import org.zjkoye.crm.common.Result;
import org.zjkoye.crm.entity.Business;
import org.zjkoye.crm.entity.Customer;
import org.zjkoye.crm.service.BusinessService;
import org.zjkoye.crm.service.CustomerService;
import org.zjkoye.crm.service.RegionService;
import org.zjkoye.crm.utils.ThreadLocalUtil;

import java.util.Map;

@RestController
@RequestMapping("/business")
public class BusinessController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private RegionService regionService;

    @GetMapping("/pageList")
    @Operation(summary = "客户列表分页查询")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "pageSize", required = true, description = "每页显示的条数"),
            @Parameter(name = "currentPage", required = true, description = "要查询的页"),
            @Parameter(name = "name", description = "客户姓名", required = false)
    })
    public Result<PageResultBean<Business>> pageList(@RequestParam int pageSize, @RequestParam int currentPage, @Nullable @RequestParam String businessName) {
        businessService.updateBusinessWorkOrderStatus();
        IPage<Business> page = businessService.pageList(pageSize, currentPage, businessName);
        if (page == null) {
            return Result.error("查询失败");
        }
        PageResultBean<Business> pageResultBean = new PageResultBean<Business>(page.getTotal(), page.getRecords());
        //logger.info(String.valueOf(pageSize));
        //logger.info(Result.success(PageResultBean.getInstance(page.getTotal(), page.getRecords())).toString());
        logger.info(businessName);
        return Result.success(PageResultBean.getInstance(page.getTotal(), page.getRecords()));

    }


    @PostMapping("/add")
    @Operation(summary = "添加客户")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> addUser(@RequestBody Business business) {

        if (business.getCustomerId() == null || business.getCustomerId() == 0) {
            return Result.error("错误 请检查客户ID是否为空");
        }

        // 检查客户ID是否存在于数据库中
        Customer customer = customerService.getById(business.getCustomerId());
        if (customer == null) {
            return Result.error("客户ID无效，请检查客户ID是否正确");
        }

        if(!regionService.isExist(business.getRegionName()))
            return Result.error("当前地区未添加到地区表中请联系管理员");

        // 检查业务状态
        if (!"正式业务".equals(business.getBusinessStatus()) &&
                !"试用业务".equals(business.getBusinessStatus()) &&
                !"拆机业务".equals(business.getBusinessStatus()) &&
                !"试用结束业务".equals(business.getBusinessStatus())) {
            return Result.error("业务状态无效");
        }

        // 检查运营商工单类型
        if (business.getOperatorOrderType() != null &&
                !"装机".equals(business.getOperatorOrderType()) &&
                !"移机".equals(business.getOperatorOrderType()) &&
                !"拆机".equals(business.getOperatorOrderType())) {
            return Result.error("运营商工单类型无效");
        }

        // 检查装机地址
        if (business.getInstallationAddress() == null || business.getInstallationAddress().isEmpty()) {
            business.setInstallationAddress(customer.getAddress()); // 默认为客户地址
        }

        // 设置操作人
        Map<String, Object> userSession = ThreadLocalUtil.get();
        String operator = (String) userSession.get("name");
        business.setOperator(operator);

        // 设置默认字段
        business.setOrderStatus("未派单");
        business.setDataStatus("新建");

        // 保存业务信息
        boolean isSuccess = businessService.save(business);
        if (isSuccess) {
            return Result.success("业务添加成功");
        } else {
            return Result.error("业务添加失败");
        }
    }
    @PutMapping("/update")
    @Operation(summary = "修改用户信息")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public Result<String> update(@RequestBody Business business) {
        // 检查业务ID
        if (business.getBusinessId() == null || business.getBusinessId() == 0) {
            return Result.error("业务ID无效");
        }
        if(customerService.getCustomerById(business.getCustomerId()) == null)
        {
            return Result.error("该客户不存在或者已经被删除");
        }

        if(!regionService.isExist(business.getRegionName()))
            return Result.error("当前地区未添加到地区表中请联系管理员");
        // 检查业务状态
        if (!"正式业务".equals(business.getBusinessStatus()) &&
                !"试用业务".equals(business.getBusinessStatus()) &&
                !"拆机业务".equals(business.getBusinessStatus()) &&
                !"试用结束业务".equals(business.getBusinessStatus())) {
            return Result.error("业务状态无效");
        }

        // 检查运营商工单类型
        if (business.getOperatorOrderType() != null &&
                !"装机".equals(business.getOperatorOrderType()) &&
                !"移机".equals(business.getOperatorOrderType()) &&
                !"拆机".equals(business.getOperatorOrderType())) {
            return Result.error("运营商工单类型无效");
        }

        // 设置更新者
        Map<String, Object> userSession = ThreadLocalUtil.get();
        String operator = (String) userSession.get("name");
        business.setOperator(operator);

        boolean isSuccess = businessService.updateById(business);
        if (isSuccess) {
            return Result.success("业务修改成功");
        } else {
            return Result.error("业务修改失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "用户id")
    })
    public Result<String> delete(@PathVariable int id) {
        boolean result = businessService.deleteById(id);
        if (!result) {
            return Result.error("删除失败");
        }
        return Result.success();
    }
    @GetMapping("/getuserById")
    @Operation(summary = "根据id查询客户信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "客户id")
    })
    public Result<Business> getUserById(@RequestParam int id) {
        Business user = businessService.getCustomerById(id);
        if (user == null) {
            return Result.error("获取用户信息失败");
        }
        return Result.success(user);
    }
}
